<template>
  <div class="left-menu">
    <div class="organ-options">
      <el-checkbox-group v-model="selectedOrganIds" @change="handleOrganChange">
        <el-checkbox v-for="organ in organs" :key="organ.id" :label="organ.id">{{ organ.name }}</el-checkbox>
      </el-checkbox-group>
    </div>
    
    <!-- 为每个选中的器官显示独立的树形菜单 -->
    <div v-for="organData in selectedOrgansData" :key="organData.organId" class="organ-tree-section">
      <div class="organ-tree-title">{{ organData.organName }}</div>
      <el-tree
        :ref="el => setTreeRef(el, organData.organId)"
        v-if="organData.attributeMenu.length > 0"
        :data="organData.attributeMenu"
        node-key="id"
        :props="defaultProps"
        @node-click="(data) => handleNodeClick(data, organData.organId)"
        highlight-current
        default-expand-all
        show-checkbox
        @check="(data, checked) => handleCheckChange(data, checked, organData.organId)"
        check-strictly
      />
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useMedicalStore } from '@/store/medical'
import { ElTree } from 'element-plus'

const store = useMedicalStore()
const selectedOrganIds = ref([])
const treeRefs = ref(new Map())

// 计算属性获取器官列表
const organs = computed(() => store.organs)
// 修改计算属性，确保每个器官只出现一次
const selectedOrgansData = computed(() => {
  const organIds = new Set(selectedOrganIds.value)
  const uniqueOrgans = new Map()
  
  // 遍历 store 中的数据，只保留每个器官的最新数据
  store.selectedOrgansData.forEach(data => {
    if (organIds.has(data.organId)) {
      uniqueOrgans.set(data.organId, data)
    }
  })
  
  return Array.from(uniqueOrgans.values())
})

// 树形控件配置
const defaultProps = {
  children: 'children',
  label: 'name'
}

// 设置树形组件引用
const setTreeRef = (el, organId) => {
  if (el) {
    treeRefs.value.set(organId, el)
  }
}

// 组件挂载时获取器官列表
onMounted(async () => {
  console.log('LeftMenu组件挂载，开始获取器官列表')
  await store.fetchOrgans()
  console.log('器官列表获取完成:', organs.value)
  // 不再默认选择器官，等待用户手动选择
})

// 处理器官选择变化
const handleOrganChange = (organIds) => {
  console.log('器官选择变化:', organIds)
  store.selectMultipleOrgans(organIds)
}

// 处理节点点击
const handleNodeClick = (data, organId) => {
  console.log('节点点击:', data, '器官ID:', organId)
  store.selectAttribute(data, organId)
}

// 处理复选框变化
const handleCheckChange = (data, checked, organId) => {
  console.log('复选框变化:', data, checked, '器官ID:', organId)
  
  // 获取当前选中的叶子节点
  const currentCheckedLeafNodes = checked.checkedNodes ? 
    checked.checkedNodes.filter(node => !node.children || node.children.length === 0) : []
  
  // 获取当前store中该器官的叶子节点
  const currentStoreLeafNodes = store.selectedLeafNodes.filter(node => node.organId === organId)
  
  // 找出需要添加的节点（在当前选中但不在store中）
  const nodesToAdd = currentCheckedLeafNodes.filter(checkedNode => 
    !currentStoreLeafNodes.some(storeNode => storeNode.id === checkedNode.id)
  )
  
  // 找出需要移除的节点（在store中但不在当前选中）
  const nodesToRemove = currentStoreLeafNodes.filter(storeNode => 
    !currentCheckedLeafNodes.some(checkedNode => checkedNode.id === storeNode.id)
  )
  
  // 添加新选中的叶子节点
  if (nodesToAdd.length > 0) {
    nodesToAdd.forEach(leafNode => {
      store.addLeafNode(leafNode, organId)
      store.fetchLeafNodeDetail(leafNode.id)
    })
    
    // 自动勾选父级节点
    const treeRef = treeRefs.value.get(organId)
    if (treeRef) {
      nodesToAdd.forEach(leafNode => {
        const path = getNodePath(leafNode, organId)
        path.forEach(pathNode => {
          if (pathNode.id !== leafNode.id) {
            treeRef.setChecked(pathNode.id, true, false)
          }
        })
      })
    }
  }
  
  // 移除取消选中的叶子节点
  if (nodesToRemove.length > 0) {
    nodesToRemove.forEach(leafNode => {
      store.removeLeafNode(leafNode.id)
    })
  }
}

// 获取节点路径的辅助函数
const getNodePath = (node, organId) => {
  const path = []
  let current = node
  
  while (current) {
    path.unshift(current)
    if (current.parentId) {
      current = findNodeById(current.parentId, organId)
    } else {
      break
    }
  }
  
  return path
}

// 根据ID查找节点的辅助函数
const findNodeById = (nodeId, organId) => {
  const organData = selectedOrgansData.value.find(data => data.organId === organId)
  if (!organData) return null
  
  const findInTree = (nodes) => {
    for (const node of nodes) {
      if (node.id === nodeId) {
        return node
      }
      if (node.children && node.children.length > 0) {
        const found = findInTree(node.children)
        if (found) return found
      }
    }
    return null
  }
  
  return findInTree(organData.attributeMenu)
}

// 取消勾选叶子节点（供外部调用）
const uncheckLeafNode = (nodeId, organId) => {
  const treeRef = treeRefs.value.get(organId)
  if (treeRef) {
    treeRef.setChecked(nodeId, false, false)
    // 同时从store中移除该叶子节点
    store.removeLeafNode(nodeId)
  }
}

// 暴露方法给父组件
defineExpose({
  uncheckLeafNode
})
</script>

<style scoped>
.left-menu {
  height: 100%;
  border-right: 1px solid #dcdfe6;
  padding: 10px;
}

.organ-options {
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #ebeef5;
  display: flex; /* 添加：使子元素水平排列 */
  flex-wrap: nowrap; /* 修改：不允许换行 */
  overflow-x: auto; /* 添加：横向滚动 */
  white-space: nowrap; /* 添加：防止文字换行 */
}

.organ-options :deep(.el-checkbox) {
  display: inline-block; /* 修改：使多选框水平排列 */
  margin-right: 20px; /* 添加：设置多选框之间的间距 */
  margin-bottom: 8px;
}

.organ-tree-section {
  margin-bottom: 20px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  overflow: hidden;
}

.organ-tree-title {
  background-color: #f5f7fa;
  padding: 10px 15px;
  font-weight: 600;
  font-size: 14px;
  color: #303133;
  border-bottom: 1px solid #ebeef5;
}

:deep(.el-tree-node__content) {
  height: 32px;
}

:deep(.el-tree-node.is-current > .el-tree-node__content) {
  background-color: #f5f7fa;
}

:deep(.el-tree) {
  padding: 10px;
}
</style>